package com.mali.malibackendproduct.controller;

import com.mali.backendcommon.common.Result;
import com.mali.backendcommon.constant.MessageConstant;
import com.mali.backendcommon.util.AliOssUtil;
import com.mali.malibackendmodel.dto.ProductAddDTO;
import com.mali.malibackendmodel.dto.ProductEditDTO;
import com.mali.malibackendmodel.dto.ProductQueryDTO;
import com.mali.malibackendmodel.dto.ScratchpadDTO;
import com.mali.malibackendmodel.vo.*;
import com.mali.malibackendproduct.service.*;
import com.mali.backendcommon.rpc.ProductService;
import com.mali.malibackendproduct.service.ScratchpadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @Author:吴键霏
 * @Date：2024/6/16 10:43
 * @Version 1.0
 */
@RestController
@RequestMapping("/product")
@Slf4j
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ScratchpadService scratchpadService;
    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private ProxyProductService proxyProductService;

    // 分页查询
    @PostMapping("/list/{page}/{size}")
    public Result<PageVO<ProductQueryVO>> productQuery(@PathVariable("page")Long page, @PathVariable("size")Long size,
                                                       @RequestBody(required = false) ProductQueryDTO productQueryDTO){
       return productService.productPageQuery(page,size,productQueryDTO);
    }

    // 详细信息查询
    @GetMapping("/details/{productId}")
    public Result<ProductDetailsQueryVO> productDetailsQuery(@PathVariable("productId")Long productId){
        return productService.productDetailsById(productId);
    }

    /**
     * 商品请求审核
     * @param productId 商品id
     * @return
     */
    @PutMapping("/requireVerify/{productId}")
    Result productNeedVerify (@PathVariable("productId") Long productId) {
        return productService.verifyRequest(productId);
    }

    //商品审核通过
    @PutMapping("/verify/pass/{productId}")
    Result productVerifyPass (@PathVariable("productId") Long productId) {
        return productService.verifyPass(productId);
    }

    //商品审核不通过
    @PutMapping("/verify/unpass/{productId}")
    Result productVerifyUnpass (@PathVariable("productId") Long productId){
        return productService.verifyUnpass(productId);
    }

    //商品上下线接口
    @PutMapping("/line/{productId}/{status}")
    Result productLine (@PathVariable("productId") Long productId, @PathVariable("status") Integer status) {
        return productService.line(productId, status);
    }

    /**
     * 商品兑换量折线图接口
     * @param beginTime 起始时间
     * @param endTime   结束时间
     * @return
     */
    @GetMapping("/exchange")
    Result productExchange (@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTime,
                            @DateTimeFormat(pattern = "yyyy-MM-dd")  LocalDate endTime) {
        return ordersService.getProductExchange(beginTime, endTime);

    }
    @GetMapping("/hello")
    public Result hello()
    {
        throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
    }

    @GetMapping("/top")
    Result productsTop(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTime,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        return ordersService.productsTop(beginTime, endTime);
    }

    @GetMapping("/buyway")
    Result productsBuyWay(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTime,
                          @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        return ordersService.buyWay(beginTime, endTime);
    }

    @RequestMapping(path="/upload", method = RequestMethod.POST)
    @ResponseBody
    public Result createProduct(@RequestBody ProductAddDTO productAddDTO){
        return productService.addProductAndPrice(productAddDTO);
    }

    @RequestMapping(path="/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateProduct(@RequestBody ProductEditDTO productEditDTO){
        return productService.updateProductAndPrice(productEditDTO);
    }

    @RequestMapping(path="/scratchpad", method = RequestMethod.POST)
    @ResponseBody
    public Result addOrUpdateProduct(@RequestBody ScratchpadDTO scratchpadDTO){
        return scratchpadService.addOrUpdateScratchpadService(scratchpadDTO);
    }

    @RequestMapping(path="/scratchpad", method = RequestMethod.GET)
    @ResponseBody
    public Result getScratchpadByUserId(){
        return scratchpadService.getScratchpadByUserId();
    }

    @RequestMapping(path="/scratchpad/delete", method = RequestMethod.GET)
    @ResponseBody
    public Result deleteScratchpadByUserId(){
        return scratchpadService.deleteScratchpadByUserId();
    }

    @RequestMapping(path="/proxy/get/{productId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<ProxyByProductIdVO>> getProxiesByProductId(@PathVariable("productId") Long productId){
        return proxyProductService.getProxiesByProductId(productId);
    }

    @RequestMapping(path="/proxy/add/{productId}/{userId}", method = RequestMethod.POST)
    @ResponseBody
    public Result addProxy(@PathVariable("productId") Long productId,@PathVariable("userId") Long userId){
        return proxyProductService.addProxy(productId,userId);
    }

    @RequestMapping(path="/proxy/delete/{productId}/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Result deleteProxy(@PathVariable("productId") Long productId,@PathVariable("userId") Long userId){
        return proxyProductService.deleteProxy(productId,userId);
    }


    @PostMapping("/image/upload")
    public Result upload(MultipartFile file)
    {

        try {
            String originalName=file.getOriginalFilename();
            String fileType=originalName.substring(originalName.lastIndexOf("."));
            String fileEndName= UUID.randomUUID().toString()+fileType;
            String filePath=aliOssUtil.upload(file.getBytes(), fileEndName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败，{}",e);
        }
        return Result.error("文件上传失败");

    }
}
